<template>
  <div class="role">
    <el-card>
      <el-form :inline="true" class="form">
        <el-form-item label="用户名:">
          <el-input placeholder="请输入查询名" v-model="keyword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="search"
            :disabled="keyword ? false : true"
          >
            搜索
          </el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin-top: 20px">
      <el-button type="primary" icon="Plus" @click="addRole">
        添加职位
      </el-button>
      <el-table border :data="RoleArr" style="margin-top: 10px">
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column prop="id" label="ID" align="center"></el-table-column>
        <el-table-column
          prop="roleName"
          label="用户名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template #="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setPermisstion(row)"
            >
              分配权限
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateRole(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`你确定要删除${row.username}?`"
              @confirm="removeRole(row.id)"
              width="260px"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 9, 11]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        :small="small"
        :pager-count="9"
        @size-change="getHasRole"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      :title="RoleParams.id ? '更新职位' : '添加职位'"
      width="500"
    >
      <el-form :model="RoleParams" :rules="rules" ref="form">
        <el-form-item label="职位名称" prop="roleName">
          <el-input
            placeholder="请你输入职位名称"
            v-model="RoleParams.roleName"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer v-model="drawer" direction="rtl" size="30%">
      <template #header>
        <h4>分配菜单与按钮的权限</h4>
      </template>
      <template #default>
        <el-tree
          ref="tree"
          style="max-width: 600px"
          :data="menuArr"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="[9]"
          :props="defaultProps"
        />
      </template>
      <template #footer>
        <el-button type="default" @click="cancel">取消</el-button>
        <el-button type="primary" @click="hander">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import type {
  RoleResponseData,
  Records,
  RoleData,
  MenuList,
  MenuResponseData,
} from '@/api/acl/role/type'
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqRemoveRole,
  reqSetPermisstion,
  reqAllMenuList,
} from '@/api/acl/role/index'
import useLayOutSettingStore from '@/store/modules/setting.ts'
import { ElMessage } from 'element-plus'
const useSettingStore = useLayOutSettingStore()
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const small = ref(false)
const keyword = ref<string>('')
const RoleArr = ref<Records>([])
const drawer = ref<boolean>(false)
const dialogVisible = ref(false)
const menuArr = ref<MenuList>([])
const selectArr = ref<number[]>([])
const tree = ref()
//获取form组件实例
let form = ref<any>()
//收集新增岗位数据
let RoleParams = reactive<RoleData>({
  roleName: '',
})
const getHasRole = async (page = 1) => {
  currentPage.value = page
  let result: RoleResponseData = await reqAllRoleList(
    currentPage.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code === 200) {
    RoleArr.value = result.data.records
    total.value = result.data.total
  }
}
const handleCurrentChange = () => {
  getHasRole(currentPage.value)
}
onMounted(() => {
  getHasRole()
})
const save = async () => {
  //表单校验结果,结果通过在发请求、结果没有通过不应该在发生请求
  await form.value.validate()
  let result: any = await reqAddOrUpdateRole(RoleParams)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: RoleParams.id ? '更新成功' : '添加成功',
    })
    dialogVisible.value = false
    getHasRole(RoleParams.id ? currentPage.value : 1)
  }
}
const search = async () => {
  //再次发请求根据关键字
  getHasRole()
  keyword.value = ''
}
const reset = () => {
  useSettingStore.refresh = !useSettingStore.refresh
}
const removeRole = async (id: number) => {
  let result: any = await reqRemoveRole(id)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    getHasRole(
      RoleArr.value.length > 1 ? currentPage.value : currentPage.value - 1,
    )
  }
}
const cancel = () => {
  dialogVisible.value = false
  //清空数据
  Object.assign(RoleParams, {
    roleName: '',
    id: 0,
  })
  //清空上一次表单校验错误结果
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
// 添加职位回调
const addRole = () => {
  dialogVisible.value = true
  //清空数据
  Object.assign(RoleParams, {
    roleName: '',
    id: 0,
  })
  //清空上一次表单校验错误结果
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
const updateRole = (row: RoleData) => {
  dialogVisible.value = true
  Object.assign(RoleParams, row)
  //清空上一次表单校验错误结果
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
//自定义校验规则的回调
const validatorRoleName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('职位名称至少两位'))
  }
}

const setPermisstion = async (row: RoleData) => {
  drawer.value = true
  Object.assign(RoleParams, row)
  let result: MenuResponseData = await reqAllMenuList(row.id as number)
  if (result.code == 200) {
    menuArr.value = result.data
    selectArr.value = filterSelectNode(menuArr.value, [])
  }
}
const filterSelectNode = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.children.length == 4) {
      initArr.push(item.id)
    }
    if (item.children.length > 0) {
      filterSelectNode(item.children, initArr)
    }
  })
  return initArr
}
const hander = async () => {
  const roleId = RoleParams.id as number
  const arr = tree.value.getCheckedKeys()
  const arr1 = tree.value.getHalfCheckedKeys()
  const permissionId = arr.concat(arr1)
  let result: any = await reqSetPermisstion(roleId, permissionId)
  if (result.code == 200) {
    drawer.value = false
    ElMessage({
      type: 'success',
      message: '分配权限成功',
    })
  }
}
//职位校验规则
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
const defaultProps = {
  children: 'children',
  label: 'name',
}
</script>

<style lang="scss" scoped>
.role {
  .form {
    display: flex;
    justify-content: space-between;
  }
}
</style>
